<template>
  <ContentWrap>
    <!-- 搜 索工作栏 -->
    <el-form class="-mb-15px" :model="form" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item prop="searchValue">
        <el-input
          v-model="form.searchValue"
          clearable
          placeholder="请输入搜索内容"
          @change="handleQuery"
        >
          <template #prefix>
            <Icon icon="ep:search" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="openForm()">
          <Icon icon="ep:plus" class="mr-5px" /> 新 增
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-tooltip
          placement="top-start"
          content='表格上方输入框为查询输入框，可在里面输入搜索关键字字符串，鼠标焦点移出输入框后进行搜索操作，表格中将显示查询结果，搜索关键字字符串为模糊查询。如有多个搜索内容，可以空格进行分隔。第二种搜索方式为"复杂搜索"，点击"复杂搜索"按钮后，可以设置多条件复杂搜索。第三种搜索方式为“筛选”，表格中表头列中如果有“下拉”标志按钮，则可以点击，弹出下拉复选框，选择后，点击下拉复选框中“筛选”文字，则可以进行数据的筛选操作，可快速查找到自己想看的数据，筛选结果将显示在表格中。表格中表头列中如果有“上下”标志按钮，则可以点击上按钮或下按钮进行排序，可快速查找或对比数据。排序结果不是针对于分页列表中本页内容，而是针对于分页列表中所有内容。本模块暂不支持多列依序排列，只支持针对于某一列的排序，所以点击排序按钮后，以前的排序结果将无效。排序结果只针对于本次数据浏览，不会影响到数据库的实际结果。当页面刷新后，排序需重新进行。'
        >
          <el-button
            type="primary"
            plain
            :disabled="queryBuilderShow"
            @click="queryBuilderShow = true"
          >
            复杂搜索
          </el-button>
        </el-tooltip>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap v-if="queryBuilderShow">
    <el-row
      ><el-col :span="16">
        <tiny-query-builder
          ref="queryBuilder"
          :config="config"
          :query="query"
          :on-query-change="queryChange" /></el-col
      ><el-col :span="8">
        <el-button type="primary" plain @click="handleQuery"> 搜 索 </el-button>
        <el-button type="primary" plain @click="queryBuilderShowFalse">
          清除搜索条件后隐藏
        </el-button></el-col
      ></el-row
    >
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      border
      highlight-current-row
      stripe
      @sort-change="sortChange"
      @filter-change="filterChange"
      show-summary
    >
      <el-table-column type="selection" width="64" />
      <el-table-column type="index" label="序 号" width="80" align="center" fixed />
      <el-table-column sortable="true" label="名 称" align="center" prop="name" />
      <el-table-column sortable="true" label="编 码" align="center" prop="code" />
      <el-table-column label="操 作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="openForm(scope.row.id)"> 编 辑 </el-button>
          <el-button link type="danger" @click="handleDel(scope.row.id)"> 删 除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="form.pageNum"
      v-model:limit="form.pageSize"
      @pagination="getPage"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <update ref="formRef" @success="getPage" />
</template>
<script setup lang="tsx" name="SystemPost">
import { QueryBuilder as TinyQueryBuilder } from '@opentiny/vue'
import * as Api from '@/api/userCenter/dept/post'
import update from './update.vue'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const queryBuilderShow = ref(false)

const queryBuilder = ref()

import { operators, defaultOptions } from '@/utils/queryBuilder'

const config = {
  operators,
  ...defaultOptions,
  combinators: [
    {
      name: 'and',
      label: '且'
    },
    {
      name: 'or',
      label: '或'
    }
  ],
  fields: [
    {
      name: 'name',
      label: '名 称'
    }
  ]
}

import { uuid } from '@/utils'

const query = ref({
  id: uuid(),
  combinator: 'and',
  not: false,
  rules: []
})

const queryChange = async (data) => {
  query.value = data
}

const queryBuilderShowFalse = async () => {
  query.value = {
    id: uuid(),
    combinator: 'and',
    not: false,
    rules: []
  }
  queryBuilderShow.value = false
}

const loading = ref(false) // 列表的加载中
const total = ref<number>(0) // 列表的总页数
const list = ref([]) // 列表的数据
const form = ref({
  query: '',
  pageNum: 1,
  pageSize: 20,
  searchValue: '',
  filters: '',
  sortOrder: 'DESC', // 排序,asc／desc
  sortName: 'order_num', // 排序,字段
  code: '',
  name: '',
  status: undefined
})
let filterArrLet: any[] = []

const queryFormRef = ref() // 搜 索的表单

/** 查询岗位列表 */
const getPage = async () => {
  loading.value = true
  try {
    const data = await Api.getPostPage(form)
    list.value = data.list
    total.value = data.total
  } catch (t) {
    console.log(t)
    loading.value = false
    message.error('查询列表失败')
  } finally {
    loading.value = false
  }
}

/** 搜 索按钮操作 */
const handleQuery = () => {
  form.value.query = ''

  if (queryBuilderShow.value) {
    form.value.query = encodeURIComponent(JSON.stringify(query.value))
  }
  form.value.pageNum = 1
  getPage()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (id?: string) => {
  if (!id) {
    id = uuid()
  }
  formRef.value.open(id)
}

/** 删除按钮操作 */
const handleDel = async (id: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await Api.del(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getPage()
  } catch {}
}

const sortChange = async (data) => {
  form.value.sortOrder = data.order.replace(/ending$/, '')
  form.value.sortName = data.prop

  getPage()
}

const filterChange = async (filters) => {
  filterArrLet.push(filters)
  form.value.filters = encodeURIComponent(JSON.stringify(filterArrLet))

  getPage()
}

/** 初始化 **/
onMounted(() => {
  getPage()
})
</script>
